import React, { useState } from "react";
import { Link, withRouter } from "react-router-dom";
import { Layout, Avatar, Menu, Dropdown, Modal, message } from "antd";
import { UserOutlined } from "@ant-design/icons";
import "./index.less";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import localUtils from "@/utils/local";
import ResetPs from "./resetPs";
import {
  userUpdateps
} from "@/api/user";

const { Header } = Layout;
const { confirm } = Modal;

function Headers(props) {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const logout = () => {
    confirm({
      title: "确定要退出登录吗？",
      icon: <ExclamationCircleOutlined />,
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        localUtils.user = {};
        localUtils.removeUser();
        props.history.replace("/login");
      }
    });
  };
  const resetPs = () => {
    setIsModalVisible(true)
  }
  const menu = () => {
    return (
      <Menu>
        <Menu.Item key='1'>
          <div onClick={logout}>退出登录</div>
        </Menu.Item>
        <Menu.Item key='2'>
          <div onClick={resetPs}>修改密码</div>
        </Menu.Item>
      </Menu>
    );
  };
  const onOk = val => {
    userUpdateps({ ...val })
      .then(res => {
        if (res.data.code === 200) {
          handleCancel()
          message.success("密码修改成功")
          return
        }
        message.error(res.data.msg)
      })
  }
  const handleCancel = () => {
    setIsModalVisible(false)
  }
  const { username } = localUtils.user;
  return (
    <Header className='header'>
      <Link to='/'>
        <div className='logo'>React后台管理系统</div>
      </Link>

      <div className='userInfo'>
        <span>欢迎, {username}</span>
        <Dropdown overlay={menu} placement='bottomRight'>
          <Avatar className='user' icon={<UserOutlined />} />
        </Dropdown>
      </div>
      <Modal
        title='添加用户'
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <ResetPs
          onOk={onOk}
          onCancel={handleCancel}
        />
      </Modal>
    </Header>
  );
}

export default withRouter(Headers);
